#include <Windows.h>

#ifndef MEMORY_HANDLE_H
#define MEMORY_HANDLE_H

void *heap[8192];

CRITICAL_SECTION cs;
bool init = false;

void *operator new(size_t s){
	if(!init){
		InitializeCriticalSection(&cs);
		init = true;
	}
	
	EnterCriticalSection(&cs);
	
	for(int i = 0; i < 8192; i++){
		if(heap[i] == NULL){
			heap[i] = malloc(s);
			LeaveCriticalSection(&cs);
			return heap[i];
		}
	}

	LeaveCriticalSection(&cs);
	
	throw "allocation fail : no free memory";
	return NULL;
}
void *operator new[](size_t s){
	if(!init){
		InitializeCriticalSection(&cs);
		init = true;
	}
	
	EnterCriticalSection(&cs);
	
	for(int i = 0; i < 8192; i++){
		if(heap[i] == NULL){
			heap[i] = malloc(s);
			LeaveCriticalSection(&cs);
			return heap[i];
		}
	}
	
	LeaveCriticalSection(&cs);
	
	throw "allocation fail : no free memory";
	return NULL;
}

void operator delete(void *p){
	EnterCriticalSection(&cs);
	for(int i = 0; i < 8192; i++){
		if(heap[i] == p){
			free(heap[i]);
			heap[i] = NULL;
		}
	}
	LeaveCriticalSection(&cs);
}
void operator delete[](void *p){
	EnterCriticalSection(&cs);
	for(int i = 0; i < 8192; i++){
		if(heap[i] == p){
			free(heap[i]);
			heap[i] = NULL;
		}
	}
	LeaveCriticalSection(&cs);
}


#endif